package ltd.followkba.task;

import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URLEncoder;
import java.util.Random;

import ltd.followkba.MAPP;
import ltd.followkba.comment.MUTIL;
import ltd.followkba.comment.ResultNet;
import main.MAPI;



public class UploadApp33 extends App33 {
    public BFileBase mBFileBase;
    public BDbsAccount mBDbsAccount;

    
    public UploadApp33(String mixAccount, int worksType) {
        if (mixAccount != null) {
            String[] params = mixAccount.split(":");
            gsUserID = "";
            gsToken = "";
            if (params.length > 1) {
                gsUserID = params[0];
                gsToken = "T" + params[1];
            }
        }
//        gsWorkPath = MRAM.gsCachePath;
    }
    public void setInfo(String userIdS, BDbsAccount bDbsAccount, String worksName){
        mBFileBase = new BFileBase();
        mBFileBase.WorksName = worksName;
        mBFileBase.UserID = MAPI.STRING_DEC32(userIdS);
        mBDbsAccount = bDbsAccount;
    }
    private void setMessage(String text){
        setMessage(text, true);
    }
    private void setMessage(String text, boolean fileLog){
        if (mBDbsAccount != null) {
            mBDbsAccount.Message = text;
        };
        MLOG(text);
        if (fileLog && mBFileBase != null) {
            MAPP.MLOG_FILE(mBDbsAccount, String.format("上传:%s", mBFileBase.WorksName), text);
        }
    }

    public String uploadPhoto(String fileName){
        String gsLocal_1 = MUTIL.GET_RANDOM_ID_STRING();
        String gsLocal_2 = "";
        if ("".equals(gsUserID)){
            return "error：没有设置用户ID";
        }
        int g4Local_1 = 0;
        String upPhotoFile = gsLocal_1 + "crop_photo.jpg";
        MLOG("uploadPhotoFile A "+ fileName+" "+ MAPI.GET_FILE_LENGTH(fileName)+" "+upPhotoFile);
        gsLocal_1 = "http://upimgapi.changba.com/ktvbox.php?ac=uploaduserheadphoto&bless=1&channelsrc=market_%E8%85%BE%E8%AE%AF&macaddress=" + gsMac;
        gsLocal_1 += "&deviceid=" + gsMac + gsVersion;//"&version=8.6.2";
//MLOG(gsLocal_1);MLOG(mChangBa.mUserID);MLOG(mChangBa.mToken);
        OkHttpClient mOkHttpClient = new OkHttpClient();
        File file = new File(fileName);
        Response response = null;
        g4Local_1 = 0;
        do {
            try {
                RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                RequestBody requestBody = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"userid\""), RequestBody.create(null, gsUserID))
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"curuserid\""), RequestBody.create(null, gsUserID))
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"token\""), RequestBody.create(null, gsToken))
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"imgdata\";filename=\"" + upPhotoFile + "\""), fileBody)
                        .build();
                Request request = new Request.Builder()
                        .url(gsLocal_1 + MUTIL.GET_SERET_USER_INFO(gsLocal_1))
                        .header("User-Agent", gsUserAgent)
                        .post(requestBody)
                        .build();
                response = mOkHttpClient.newCall(request).execute();
                gsLocal_2 = response.body().string();
                MLOG("uploadPhotoFile C "+gsLocal_2);
                if (response.code() < 200 || response.code() > 201) {
                }
                else {
                    gsLocal_2 = MUTIL.GET_JSON_STRING(gsLocal_2, "errorcode");
                    MLOG("uploadPhotoFile D "+gsLocal_2);
                    if ("ok".equals(gsLocal_2)) {
                        //         MAPI.DELETE_FILE(locPhotoFile);
                        return "ok";
                    }
                }
            } catch (IOException e) {
            }
            MAPI.MSLEEP(1000);
        } while (++g4Local_1 < 5);
        return "error";
    }
    public String makeSetting(String musicID, String songName, String intro, String area){
        mBFileBase.RankName = area;
        String gsLocal_1 = "&songid=" + musicID + "&music_gain=-3&sinaAt=&shareFlag=sina_&voice_gain=0&shareContent=" + URLEncoder.encode(intro);
        gsLocal_1 += "&content=" + URLEncoder.encode(intro) + "&songname=" + URLEncoder.encode(songName);
        return gsLocal_1 + "&area=" + URLEncoder.encode(area) + "&effect=13";
    }

    public void returnBusyMessage(int step, int busy, String message){
//        MLOG(step + " " + busy + " " + message);
        setMessage(String.format("step:%s busy:%s %s", step, busy, message));
    }
    
    public String uploadMediaFile(boolean video, String fileName, String setting) {
        String gsLocal_1;
        String gsLocal_2;
        String gsLocal_3;
        String gsLocal_4;
        String gsLocal_5;
        String gsLocal_6;

        String area = mBFileBase != null ? mBFileBase.RankName : "";
        if (!video) {
            gsLocal_1 = "http://upworkapi.changba.com/ktvbox.php?ac=uploaduserworkwithqiniu_updatedb";
            setMessage(String.format("%sMP3(%s)%s", area, MAPI.GET_FILE_LENGTH(fileName), fileName));
        }
        else {
            gsLocal_1 = "http://upworkapi.changba.com/ktvbox.php?ac=uploaduserworkwithqiniu_videodb";
            setMessage(String.format("%sMP4(%s)%s", area, MAPI.GET_FILE_LENGTH(fileName), fileName));
        }
        gsLocal_1 += "&bless=1&channelsrc=market_%E8%85%BE%E8%AE%AF&macaddress=" + gsMac + "&deviceid=" + gsMac + gsVersion;//"&version=8.6.2";
        gsLocal_2 = "tags=&curuserid=" + gsUserID + "&qqAt=" + setting + "&token=" + gsToken +"&isprivate=0&device=" + gsDevice + "&duetid=0&longitude=" + gsLongitude;
        gsLocal_2 += "&dpi=0&latitude=" + gsLatitude + "&offset=0&earphone=1&eq=0&";

        ResultNet resultNet = new ResultNet();
        gsLocal_3 = WriteToSvr(gsLocal_1, gsLocal_2);
        setMessage("uploadMediaFile "+gsLocal_3, false);
        if (MakeStdReturn(gsLocal_3, resultNet) == true) {
            gsLocal_1 = MUTIL.GET_JSON_STRING(resultNet.nextJason, "signature");
            int gReturnStep=0;
            gsLocal_2 = "UpToken " + gsLocal_1;
            gsLocal_1 = "http://upload.qiniu.com";
            RandomAccessFile gfLocal_1 = null;
            byte[] gpLocal_1 = new byte[262144];
            int g4Local_1 = (int) MAPI.GET_FILE_LENGTH(fileName);
            int g4Local_2;
            int g4Local_3;
            int g4Local_4;
            int g4Local_5 = g4Local_1;
            byte gLocal_1 = 0;
            g4Local_2 = 0;
            gsLocal_5 = "";
            gsLocal_6 = "";
            try {
                gfLocal_1 = new RandomAccessFile(fileName, "r");
                do {
                    if (g4Local_1 > 4194304){
                        g4Local_3 = 4194304;
                        g4Local_1 -= 4194304;
                    }
                    else {
                        g4Local_3 = g4Local_1;
                        g4Local_1 = 0;
                    }
                    gsLocal_3 = String.format("/mkblk/%d", g4Local_3);
                    do {
                        if (g4Local_3 > 262144){
                            g4Local_4 = 262144;
                            g4Local_3 -= 262144;
                        }
                        else {
                            g4Local_4 = g4Local_3;
                            g4Local_3 = 0;
                        }
                        gfLocal_1.read(gpLocal_1, 0, g4Local_4);
                        gsLocal_4 = qiniu_com_block(gsLocal_1 + gsLocal_3, gsLocal_2, g4Local_4, gpLocal_1);
                        MLOG(gsLocal_4);
                        if ("".equals(gsLocal_4)){
                            returnBusyMessage(50, 100, "upload.qiniu.com没有返回");
                            break;
                        }
                        gsLocal_6 = MUTIL.GET_JSON_STRING(gsLocal_4, "ctx");
                        if ("".equals(gsLocal_6)){
                            returnBusyMessage(60, 100, "upload.qiniu.com返回出错");
                            break;
                        }
                        gsLocal_3 = MUTIL.GET_JSON_STRING(gsLocal_4, "offset");
                        gsLocal_3 = "/bput/" + gsLocal_6 + "/" + gsLocal_3;
                        g4Local_2 += g4Local_4;
                        setMessage("上传：" + MUTIL.GET_PERCENT_COUNT(g4Local_2, g4Local_5) + "%", false);
                    } while (g4Local_3 > 0);
                    if (gLocal_1 > 0){
                        gsLocal_5 += ",";
                    }
                    gLocal_1 = 1;
                    gsLocal_5 += gsLocal_6;
                } while (g4Local_1 > 0);
                MLOG("返回A "+g4Local_2 +" "+ g4Local_5);
                if (g4Local_2 == g4Local_5){
                    returnBusyMessage(100, 0, "");
                    gsLocal_3 = String.format("/mkfile/%d/mimeType/YXBwbGljYXRpb24vb2N0ZXQtc3RyZWFt/fname/cmVjb3JkXzEubXA0", g4Local_2);
                    gsLocal_4 = qiniu_com_block(gsLocal_1 + gsLocal_3, gsLocal_2, gsLocal_5.length(), gsLocal_5.getBytes());
//MDWORD(0xc3);MLOG(gsLocal_4);
                    if (!video) {
                        gsLocal_3 = MUTIL.GET_JSON_STRING(gsLocal_4, "result");
                        if ("ok".equals(gsLocal_3)) {
                            returnBusyMessage(100, 100, "");
                            gfLocal_1.close();
                            return "ok";
                        } else {
                            returnBusyMessage(gReturnStep, 100, "返回确认出错：" + gsLocal_4);
                        }
                    }
                    else {
                        gsLocal_3 = MUTIL.GET_JSON_STRING(gsLocal_4, "hash");
                        if (!"".equals(gsLocal_3)) {
                            returnBusyMessage(100, 100, "");
                            gfLocal_1.close();
                            return "ok";
                        } else {
                            returnBusyMessage(gReturnStep, 100, "返回确认出错：" + gsLocal_4);
                        }
                    }
                }
                else {
                    returnBusyMessage(gReturnStep, 100, "上传的文件不完整");
                }
                gfLocal_1.close();
            } catch (IOException e) {
                returnBusyMessage(gReturnStep, 100, "mp4文件出错");
            }
            return "error" + gsLocal_3;
        }
//MLOG("recruitinginfo "+MUTIL.GET_JSON_STRING(gsLocal_1, "recruitinginfo"));
        return resultNet.message;
    }
    public String qiniu_com_block(String destUrl, String Authorization, int length, byte[]in_data) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Response response = null;
        String gsLocal_1 = "";
//MLOG("qiniu_com_block "+destUrl);
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8"), in_data, 0, length);
            Request request = new Request.Builder()
                    .url(destUrl)
                    .header("Authorization", Authorization)
                    .header("User-Agent", gsUserAgent)
                    .post(requestBody)
                    .build();
            response = mOkHttpClient.newCall(request).execute();
            gsLocal_1 = response.body().string();
//MLOG("qiniu_com_block "+response.code());MLOG(gsLocal_1);
            if (response.code() != 200) {
                return "error";
            }
        } catch (IOException e) {
        }
        return gsLocal_1;
    }



    public void DELAY_RANDOM_SECOND(int second) {
        second = second * 1000;
        Random random = new Random();
        int g4Random = Math.abs(random.nextInt()) % second;
        MAPI.MSLEEP((second / 2) + g4Random);
    }
    public String WriteToSvr(String destUrl, String param) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Response response = null;
        String gsLocal_1 = "";
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8"), param);
            Request request = new Request.Builder()
                    .url(destUrl + MUTIL.GET_SERET_USER_INFO(destUrl))
                    .header("Cb-X-Seqid", "t=0;n=23;d=0")
                    .header("User-Agent", gsUserAgent)
                    .post(requestBody)
                    .build();
            response = mOkHttpClient.newCall(request).execute();
            gsLocal_1 = response.body().string();
//MLOG(response.code());MLOG(gsLocal_1);
            if (response.code() != 200) {
                return "error";
            }
        } catch (IOException e) {
        }
        return gsLocal_1;
    }



}
